<?php

namespace app\admin\command;

use app\common\model\Artificer;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Log;

class RescueDistribution extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('rescue_distribution')
            ->addArgument('name', Argument::OPTIONAL, "your name")
            ->addOption('city', null, Option::VALUE_REQUIRED, 'city name')
            ->setDescription('救援任务自动分配距离最近的技工');
    }

    protected function execute(Input $input, Output $output)
    {

        Db::startTrans();
        try {
            $orderModel =  model('app\common\model\order\Rescue');
            // 技工未接单；或者 分配后超过5min，技工未接单，重新分配
            $tmpArr = $orderModel->where(['take_status'=>['=','10']])->whereTime('distributiontime','<=','-5 min')->column('id');
            if($tmpArr){
                foreach ($tmpArr as $k=>$v){
                    $row = $orderModel->where(['id' => $v])->lock(true)->find();
                    $artificerModel = new Artificer();
                    $params = ['distribution_status' => '20','distributiontime'=>time()];
                    //未接单技工集  排除掉
                    $params['disabled_uid'] = (!$row->artificer_id) ? null : ($row->artificer_id.($row->disabled_uid ? ','.$row->disabled_uid : '') ) ;
                    $artificer = $artificerModel->seek($row->lng,$row->lat,$params['disabled_uid']);
                    if($artificer === false){
                        Log::write('援救任务分配技工，错误信息：'.$artificerModel->getError(),'error',true);
                        $params['artificer_id'] = 0;
                        $params['distribution_status'] = '10';
                        $params['distributiontime'] = time();
                    }else{
                        $params['artificer_id'] = $artificer;
                        $params['distribution_status'] = '20';
                        $params['distributiontime'] = time();
                    }
                    //获取技工信息
                    $artificerInfo = \app\common\model\Artificer::get($artificer);
                    if($artificerInfo && $artificerInfo->lat && $artificerInfo->lng){
                        $distance = GetDistance($row->lat,$row->lng,$artificerInfo->lat,$artificerInfo->lng,2,1);
                        //计算金额
                        $extend = (new \app\common\model\order\Rescue())->getPrice($distance);
                        $params = array_merge($params,$extend);
                    }
                    $result = $row->allowField(true)->save($params);
                }
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $output->writeln('失败：'.$e->getMessage());
        }
        $output->writeln("成功：救援任务自动分配距离最近的技工或者 分配后超过5min，技工未接单，重新分配");
    }

}